<!--
 * @Author: liuhanzhuang
 * @Date: 2023-01-10 15:13:40
 * @Description: 文件描述
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    * {
      background-color: #eee;
    }

    body {
      height: 100vh;
    }

    .tags {
      margin-top: 20px;
    }

    .tag {
      padding: 3px 15px;
      background-color: orange;
      border-radius: 15px;
      color: #fff;
      margin: 0 5px;
    }

    .tag.high-bgcolor {
      background-color: rgb(160, 155, 155);
    }
  </style>
</head>

<body>
  <h2>输入选项（，）分隔</h2>
  <textarea class="inp" cols="30" rows="5"></textarea>
  <div class="tags"></div>
</body>
<script>
  let inpEl = document.querySelector('.inp');
  let tags = document.querySelector('.tags');
  inpEl.addEventListener('keyup', (ev) => {
    createSpan(ev.target.value); //根据文本域内的内容，动态创建span标签
  });
  inpEl.addEventListener('keyup', (ev) => {
    if (ev.keyCode === 13) randomTag(); //如果按下了回车，就进行抽签
  });
  function createSpan(inpValue) {
    tags.innerHTML = '';
    let res = inpValue  //按分号分隔成数组 并且去处空格
      .split('，')
      .map((item) => item.trim())
      .filter((itm) => itm.length !== 0);
    res.forEach((item) => {//创建span标签
      let spanEl = document.createElement('span');
      spanEl.className = 'tag';
      spanEl.textContent = item;
      tags.append(spanEl);
    });
  }

  function randomTag() {//随机选中一个标签
    let timer = setInterval(() => {
      //生成随机树，然后这个随机标签加上高亮效果
      let randNum = parseInt(Math.random() * tags.children.length);
      tags.children[randNum].classList.add('high-bgcolor');
      let timer2 = setTimeout(() => {//过100ms之后移除高亮效果
        tags.children[randNum].classList.remove('high-bgcolor');
      }, 100);
    }, 100);
    setTimeout(() => {//三秒之后停止
      clearInterval(timer);//清除定时器，它就不会再随机抽签了
      setTimeout(() => {
        //重新生成一个随机标签，然后给它加上高亮效果
        let randNum = parseInt(Math.random() * tags.children.length);
        tags.children[randNum].classList.add('high-bgcolor');
      }, 100);
    }, 3000);
  }
</script>

</html>